<template>
  <div class="memory-trend-chart">
    <div ref="chartRef" class="chart" v-loading="loading"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { getChartThemeOptions, watchThemeChange } from '@/utils/chartTheme'
import { formatBytes } from '@/utils/format'

const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  },
  loading: {
    type: Boolean,
    default: false
  },
  height: {
    type: String,
    default: '400px'
  }
})

const chartRef = ref(null)
const themeObserver = ref(null)
let chartInstance = null

const initChart = () => {
  if (!chartRef.value || !props.data || !props.data.series || props.data.series.length === 0) return

  // 确保容器有正确的尺寸
  const container = chartRef.value
  if (container.clientWidth === 0 || container.clientHeight === 0) {
    setTimeout(() => {
      initChart()
    }, 100)
    return
  }

  // 如果已经存在实例，先销毁它
  if (chartInstance && !chartInstance.isDisposed()) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(chartRef.value)

  // 获取系列数据
  const series = props.data.series
  const categories = props.data.categories || []

  // 获取主题配置
  const themeConfig = getChartThemeOptions()

  // 颜色配置
  const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#606266', '#FF6B6B', '#4ECDC4']

  // 格式化数值显示
  const formatValue = (value, field) => {
    const memoryFields = ['systemRss', 'systemVmapResident', 'systemVmapDirty', 'systemVmapSwap']
    if (memoryFields.includes(field)) {
      return formatBytes(value)
    }
    return value.toString()
  }

  // 生成系列配置
  const generateSeries = () => {
    return series.map((s, index) => ({
      name: s.fieldLabel,
      type: 'line',
      data: s.data,
      symbol: 'circle',
      symbolSize: 8,
      lineStyle: {
        color: colors[index % colors.length],
        width: 2
      },
      itemStyle: {
        color: colors[index % colors.length],
        borderColor: '#fff',
        borderWidth: 2
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: colors[index % colors.length] + '40' // 添加透明度
            },
            {
              offset: 1,
              color: colors[index % colors.length] + '10'
            }
          ]
        }
      }
    }))
  }

  const option = {
    backgroundColor: themeConfig.backgroundColor,
    title: {
      text: '整机内存占用趋势对比',
      textStyle: {
        fontSize: 16,
        fontWeight: 600,
        color: themeConfig.textColor
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        lineStyle: {
          color: '#999'
        }
      },
      backgroundColor: themeConfig.tooltip.backgroundColor,
      borderColor: themeConfig.tooltip.borderColor,
      textStyle: {
        color: themeConfig.tooltip.textStyle.color
      },
      formatter: (params) => {
        let html = `<div style="margin-bottom: 8px; font-weight: 600;">${params[0].axisValue}</div>`

        params.forEach(param => {
          const value = param.value
          const seriesInfo = series.find(s => s.fieldLabel === param.seriesName)
          const formattedValue = seriesInfo ? formatValue(value, seriesInfo.field) : value.toString()

          html += `
            <div style="margin: 4px 0;">
              <span style="display: inline-block; width: 8px; height: 8px; background-color: ${param.color}; border-radius: 50%; margin-right: 8px;"></span>
              <span style="color: ${param.color}; font-weight: 600;">${param.seriesName}:</span>
              <span style="margin-left: 8px;">${formattedValue}</span>
            </div>
          `
        })

        return html
      }
    },
    legend: {
      data: series.map(s => s.fieldLabel),
      textStyle: {
        color: themeConfig.textColor
      },
      top: 30,
      type: 'scroll'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%', // 增加底部空间以容纳倾斜的标签
      top: 80,
      containLabel: true,
      borderColor: themeConfig.grid.borderColor
    },
    xAxis: {
      type: 'category',
      data: categories,
      name: '测试用例',
      nameTextStyle: {
        color: themeConfig.textColor
      },
      axisLine: {
        lineStyle: {
          color: themeConfig.axisColor
        }
      },
      axisTick: {
        lineStyle: {
          color: themeConfig.axisColor
        }
      },
      axisLabel: {
        color: themeConfig.textColor,
        rotate: 45, // 文字倾斜45度以避免重叠
        interval: 0, // 显示所有标签
        fontSize: 12
      },
      splitLine: {
        lineStyle: {
          color: themeConfig.splitLineColor
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '内存占用',
      nameTextStyle: {
        color: themeConfig.textColor
      },
      axisLine: {
        lineStyle: {
          color: themeConfig.axisColor
        }
      },
      axisTick: {
        lineStyle: {
          color: themeConfig.axisColor
        }
      },
      axisLabel: {
        color: themeConfig.textColor,
        formatter: (value) => formatBytes(value) // 统一使用字节格式化
      },
      splitLine: {
        lineStyle: {
          color: themeConfig.splitLineColor
        }
      }
    },
    series: generateSeries()
  }

  chartInstance.setOption(option)
}

// 更新图表数据
const updateChart = () => {
  if (!chartInstance || chartInstance.isDisposed()) return
  initChart()
}

// 监听数据变化
watch(() => props.data, () => {
  if (props.data) {
    updateChart()
  }
}, { deep: true })

onMounted(() => {
  setTimeout(() => {
    if (props.data) {
      // 使用 nextTick 确保 DOM 完全渲染
      nextTick(() => {
        initChart()
      })
    }

    // 监听窗口大小变化
    window.addEventListener('resize', () => {
      if (chartInstance) {
        chartInstance.resize()
      }
    })

    // 监听主题变化
    themeObserver.value = watchThemeChange(() => {
      if (chartInstance && !chartInstance.isDisposed()) {
        // 重新初始化图表以应用新主题
        initChart()
      }
    })
  }, 500)
})

onUnmounted(() => {
  // 清理图表实例
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }

  // 清理主题观察者
  if (themeObserver.value) {
    themeObserver.value.disconnect()
    themeObserver.value = null
  }

  // 清理事件监听器
  window.removeEventListener('resize', () => {
    if (chartInstance) {
      chartInstance.resize()
    }
  })
})
</script>

<style scoped lang="scss">
.memory-trend-chart {
  width: 100%;
  height: 100%;

  .chart {
    width: 100%;
    height: v-bind(height);
    min-height: 300px;
  }
}
</style>